use std::collections::HashMap;
use crate::dboper;
use ibm_db::{Statement,ResultSetState::Data};

pub fn query_list(sql : String) -> Vec<HashMap<String,String>>{
    
    let pool_conn = dboper::db2::DB2POOL.get().unwrap();
    
    let conn = pool_conn.raw();

    let mut result :Vec<HashMap<String,String>> = Vec::new();
            let stmt = Statement::with_parent(&conn).unwrap();
            if let Data(mut stmt) = stmt.exec_direct(&sql).unwrap() {
                let cols = stmt.num_result_cols().unwrap();
                let mut columns :Vec<String> =Vec::new();

                for index in 1..cols {
                   let desc:String =stmt.describe_col(index.to_owned() as u16).unwrap().name;
                   columns.push(desc) ;
                }
                //println!("columns.len()={}",columns.len());

                

                while let Some(mut cursor) = stmt.fetch().unwrap(){
                    let mut row:HashMap<String,String> =HashMap::new();
                    
                    for _i in 1..cols {
                        let fieldname :String =format!("{}",columns[(_i as usize)-1]);
                        match cursor.get_data::<String>(_i as u16).unwrap() {
                            Some(val) => {
                               //println!("{},{}",&fieldname,&val); 
                               row.insert(fieldname,String::from(val));
                            },
                            None => {
                                //println!("{},NULL",&fieldname);
                            },
                        }
                    }
                    result.push(row);
                }


            };

            
            result
    
}